//
//  UITableView+UITableView_fit.m
//  06-UINavigationBar、UIToolbar和UITabBar
//
//  Created by VEER on 2022/3/9.
//

#import "UITableView+fit.h"
#import <objc/message.h>

@implementation UITableView (fit)

+ (void)load{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self exchangeInstance:[self class] selector:@selector(initWithFrame:style:) withSwizzledSelector:@selector(ev_initWithFrame:style:)];
    });
    
}

- (instancetype)ev_initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    
    UITableView *tableView = [self ev_initWithFrame:frame style:style];
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_14_5
    if (@available(iOS 15.0, *)) {
        tableView.sectionHeaderTopPadding = 0;
    }
#endif
    return tableView;
    
}

+ (BOOL)exchangeInstance:(Class)class selector:(SEL)originalSelector withSwizzledSelector: (SEL)swizzledSelector{
    
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    if(!originalMethod || !swizzledMethod){
        
        return NO;
    }
    // 若已经存在，则添加会失败
    BOOL didAddMethod = class_addMethod(class,
                                        originalSelector,
                                        method_getImplementation(swizzledMethod),
                                        method_getTypeEncoding(swizzledMethod));
    
    // 若原来的方法并不存在，则添加即可
    if (didAddMethod) {
        class_replaceMethod(class,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
    
    return YES;
}

@end
